package com.woniuxy.ai.util;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;

import java.io.IOException;

public class SimilarityClient {

    private static final OkHttpClient client = new OkHttpClient();
    private static final String API_URL = "http://localhost:8000/similarity";

    /**
     * 获取两个句子之间的语义相似度
     *
     * @param text1 句子1
     * @param text2 句子2
     * @return 相似度（0~1）
     * @throws IOException 网络异常
     */
    public static double getSimilarity(String text1, String text2) throws IOException {
        // 构建 JSON 请求体
        String jsonBody = String.format("{\"text1\": \"%s\", \"text2\": \"%s\"}", text1, text2);
        RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json"));

        // 构建请求
        Request request = new Request.Builder()
                .url(API_URL)
                .post(body)
                .build();

        // 发送请求
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            String responseBody = response.body().string();
            JSONObject json = JSON.parseObject(responseBody);
            return json.getDoubleValue("similarity");
        }
    }
}